#!/usr/bin/env ruby

require 'optparse'
require 'fileutils'

module SwitchMirror
  class Python
    VENDORS = {
      'system' => 'https://pypi.python.org/simple/',
      'aliyun' => 'https://mirrors.aliyun.com/pypi/simple/',
      'ustc' => 'https://pypi.mirrors.ustc.edu.cn/simple/',
      'douban' => 'http://pypi.douban.com/simple/',
      'v2ex' => 'http://pypi.v2ex.com/simple/',
      'opencas' => 'http://pypi.mirrors.opencas.cn/simple/',
      'tuna' => 'https://pypi.tuna.tsinghua.edu.cn/simple/'
    }.freeze

    def set(vendor_name)
      vendor_url = VENDORS[vendor_name]
      unless vendor_url
        warn "未知的镜像名称：#{mirror_name}"
        exit 2
      end

      system "pip config --user set global.index-url #{vendor_url}"
    end

    # Reading to ~/.config/pip/pip.conf
    def get
      system 'pip config --user get global.index-url'
    end

    def list
      puts <<~END_OF_VENDORS
        切换 Python 源，可用的提供商包括：

        #{
          VENDORS.keys.join("\n")
        }
      END_OF_VENDORS
    end
  end
end
